package hz.mobileproject.pda.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.codbking.widget.DatePickDialog;
import com.codbking.widget.OnSureLisener;
import com.codbking.widget.bean.DateType;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.piterwilson.audio.MP3RadioStreamDelegate;
import com.piterwilson.audio.MP3RadioStreamPlayer;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.entity.ContentSummaryIntentExtra;
import hz.mobileproject.pda.entity.request.Request_data;
import hz.mobileproject.pda.entity.request.Request_getFamilyPhoneList;
import hz.mobileproject.pda.entity.request.Rq_saveEvaluation;
import hz.mobileproject.pda.entity.response.Response_meetRecord_item;
import hz.mobileproject.pda.entity.response.Rp_loadEvaluationType;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.activity.work.PlayMP3AndEvaluateActivity;
import hz.mobileproject.pda.ui.adapter.MeetRecordingAdapter;
import hz.mobileproject.pda.ui.view.FamilyPhoneEvaluateDialog;
import hz.mobileproject.pda.utils.Base64;

/**
 * Created by Lc on 2017/10/17.
 */

public class MeetRecordingActivity extends Activity implements View.OnClickListener, OnLoadmoreListener, CompoundButton.OnCheckedChangeListener, MeetRecordingAdapter.OnItemClickListener {


    public final String Project_Name = Constance.PROJECT_NAME;

    private ImageView _datePickBtn;
    //未评价recyclerview
    private RecyclerView _recyclerView0;
    private SmartRefreshLayout _refreshLayout0;
    //已评价recyclerview
    private RecyclerView _recyclerView1;
    private SmartRefreshLayout _refreshLayout1;
    private RadioButton _rb_not_evaluate;
    private RadioButton _rb_evaluate;

    private SPUtils mSPUtils;
    private Gson mGson;
    //部门id
    private String report_dept_id;
    //部门名称
    private String report_dept_name;
    //机构号
    private String cus_number;
    //警察id  姓名
    private String police_id,police_name;
    private MeetRecordingAdapter mrAdapter0,mrAdapter1;
    //当前加载页码
    private int loadPage0 = 1;
    private int loadPage1 = 1;
    //当前选择时间
    private String mSelectQueryTime = "";

    //当前选择是否评价  0未评价
    private int mFlag = 0;
    //评价选项list
    private List<Rp_loadEvaluationType> mEvaluateList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meet_recording);
        innitView();
        innitData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadPage0 = 1;
        loadPage1 = 1;
        //从服务器获取数据
        Request_getFamilyPhoneList fp0 = new Request_getFamilyPhoneList
                ("",report_dept_id,report_dept_name,loadPage0,Request_getFamilyPhoneList.FLAG_NOT_EVALUATE);
        getMeetRecordListData(fp0 , loadMoreCallback0);
        Request_getFamilyPhoneList fp1 = new Request_getFamilyPhoneList
                ("",report_dept_id,report_dept_name,loadPage1,Request_getFamilyPhoneList.FLAG_EVALUATE);
        getMeetRecordListData(fp1 , loadMoreCallback1);
//        loadEvaluationType();
    }

    private void innitView() {
        _datePickBtn = (ImageView) findViewById(R.id.bt_select_time_all);
        _datePickBtn.setOnClickListener(this);
        _rb_evaluate = (RadioButton) findViewById(R.id.rb_evaluate);
        _rb_not_evaluate = (RadioButton) findViewById(R.id.rb_not_evaluate);
        _rb_evaluate.setOnCheckedChangeListener(this);
        _rb_not_evaluate.setOnCheckedChangeListener(this);

        _recyclerView0 = (RecyclerView) findViewById(R.id.cv_family_phone0);
        _refreshLayout0 = (SmartRefreshLayout) findViewById(R.id.smartLayout0);
        _recyclerView1 = (RecyclerView) findViewById(R.id.cv_family_phone1);
        _refreshLayout1 = (SmartRefreshLayout) findViewById(R.id.smartLayout1);
        _recyclerView0.setLayoutManager(new LinearLayoutManager(MeetRecordingActivity.this));
        _recyclerView0.setAdapter(mrAdapter0 = new MeetRecordingAdapter(
                MeetRecordingActivity.this,new ArrayList<Response_meetRecord_item>()));
        _recyclerView1.setLayoutManager(new LinearLayoutManager(MeetRecordingActivity.this));
        _recyclerView1.setAdapter(mrAdapter1 = new MeetRecordingAdapter(
                MeetRecordingActivity.this,new ArrayList<Response_meetRecord_item>()));
        _refreshLayout0.setOnLoadmoreListener(this);
        _refreshLayout1.setOnLoadmoreListener(this);
        mrAdapter0.setOnItemClickListener(this);
        mrAdapter1.setOnItemClickListener(this);
    }

    private void innitData() {
        mSPUtils = SPUtils.getInstance("app_login");
        mGson = new Gson();
        //本地获取部门id名称
        report_dept_id = mSPUtils.getString("department_id");
        report_dept_name = mSPUtils.getString("department_name");
        cus_number = mSPUtils.getString("cusnumber");
        police_id = mSPUtils.getString("police_id");
        police_name = mSPUtils.getString("police_name");
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_select_time_all://选择时间
                DatePickDialog dialog = new DatePickDialog(this);
                //设置上下年分限制
                dialog.setYearLimt(5);
                //回显当前选择时间
                if(!StringUtils.isEmpty(mSelectQueryTime)){
                    try {
                        dialog.setStartDate(new SimpleDateFormat("yyyy-MM-dd").parse(mSelectQueryTime));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //设置标题
                dialog.setTitle("选择时间");
                //设置类型
                dialog.setType(DateType.TYPE_YMD);
                //设置消息体的显示格式，日期格式
                dialog.setMessageFormat("yyyy-MM-dd HH:mm");
                //设置选择回调
                dialog.setOnChangeLisener(null);
                //设置点击确定按钮回调
                dialog.setOnSureLisener(new OnSureLisener() {
                    @Override
                    public void onSure(Date date) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        mSelectQueryTime = sdf.format(date);
//                        _datePickBtn.setText(mSelectQueryTime);
                        LogUtils.e(mSelectQueryTime);
                        //点击选择时间后 重新请求网络
                        //重置页码
                        loadPage0 = 1;
                        loadPage1 = 1;
                        getMeetRecordListData(
                                new Request_getFamilyPhoneList(
                                        mSelectQueryTime,
                                        report_dept_id,
                                        report_dept_name,
                                        loadPage0,
                                        Request_getFamilyPhoneList.FLAG_NOT_EVALUATE),
                                loadMoreCallback0);
                        getMeetRecordListData(
                                new Request_getFamilyPhoneList(
                                        mSelectQueryTime,
                                        report_dept_id,
                                        report_dept_name,
                                        loadPage1,
                                        Request_getFamilyPhoneList.FLAG_EVALUATE),
                                loadMoreCallback1);
                    }
                });
                dialog.show();
                break;
        }
    }


    /**
     * 未评价   已评价  radioButton监听
     * @param buttonView
     * @param isChecked
     */
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if(isChecked == false){
            return;
        }
        switch (buttonView.getId()){
            case R.id.rb_not_evaluate://未评价
                mFlag = Request_getFamilyPhoneList.FLAG_NOT_EVALUATE;
                _refreshLayout0.setVisibility(View.VISIBLE);
                _refreshLayout1.setVisibility(View.GONE);
                break;
            case R.id.rb_evaluate://已评价
                mFlag = Request_getFamilyPhoneList.FLAG_EVALUATE;
                _refreshLayout0.setVisibility(View.GONE);
                _refreshLayout1.setVisibility(View.VISIBLE);
                break;
        }
    }

    /**
     * item点击事件
     * @param position
     * @param item
     */
    @Override
    public void OnItemClick(final int position, final Response_meetRecord_item item) {
        ContentSummaryIntentExtra extra = new ContentSummaryIntentExtra();
        extra.setId(item.getFlowid());
        extra.setType(ContentSummaryIntentExtra.METTING_RECORD);
        extra.setPrisoner_id(item.getPr_no());
        extra.setPrisoner_name(item.getPr_name());
        extra.setTalk_effect(item.getTalk_effect());
        extra.setDanger_action(item.getDanger_action());
        extra.setDanger_evaluate(item.getDanger_evaluate());
        extra.setEmotion_evaluate(item.getEmotion_evaluate());
        extra.setFile_path(item.getFile_path());
        Intent it = new Intent(MeetRecordingActivity.this, PlayMP3AndEvaluateActivity.class);
        it.putExtra(Constance.TO_PLAYMP3EVALUATE,extra);
        startActivity(it);
    }

    /**
     *  发送请求获取评价选项列表
     */
    private void loadEvaluationType(){
        RequestParams params = new RequestParams(Constance.BASE_URL + "/" + Project_Name + "/family/loadEvaluationType");
        x.http().post(params, loadEvaluationTypeCallback);
    }

    /**
     * 发送获取列表请求
     * @param gfpl
     */
    private void getMeetRecordListData(Request_getFamilyPhoneList gfpl , Callback.CommonCallback callback){
        String fpStr = mGson.toJson(gfpl);
        LogUtils.e(fpStr);
        Request_data data = new Request_data();
        data.setData(Base64.getBase64(fpStr));
        String body_data = mGson.toJson(data);

        RequestParams params = new RequestParams(Constance.BASE_URL + "/" + Project_Name + "/family/queryMeetingRecord");
        params.setBodyContent(body_data);
        x.http().post(params, callback);
    }




    /**
     * 获取评价选项列表回调
     */
    private CustomNetCallBack loadEvaluationTypeCallback = new CustomNetCallBack() {

        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            mEvaluateList = mGson.fromJson(data,new TypeToken<ArrayList<Rp_loadEvaluationType>>() {}.getType());
            if(mEvaluateList==null || mEvaluateList.size()<=0){
                Toast.makeText(MeetRecordingActivity.this,"评价选项列表没有数据",Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("获取评价选项列表失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            LogUtils.e(ex.toString());
            ToastUtils.showLong("获取评价选项列表失败");
        }
    };

    /**
     * 未评价列表回调
     */
    private Callback.CommonCallback<String> loadMoreCallback0 = new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            try{
                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                String returnStr = Base64.getFromBase64(returnData.get("data").getAsString());
                LogUtils.e(returnStr);
                List<Response_meetRecord_item> listData = mGson.fromJson(returnStr,new TypeToken<ArrayList<Response_meetRecord_item>>() {}.getType());
                if(_refreshLayout0.isLoading()){
                    //结束下拉加载弹窗
                    _refreshLayout0.finishLoadmore();
                    mrAdapter0.addListData(listData);
                }else{
                    mrAdapter0.setListData(listData);
                }

                if(listData == null || listData.size() == 0){
                    Toast.makeText(MeetRecordingActivity.this,"未评价没有更多数据了",Toast.LENGTH_LONG).show();
                    return;
                }
                //下次加载页码应+1
                loadPage0++;
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            //结束下拉加载弹窗
            _refreshLayout0.finishLoadmore();
            mrAdapter0.clearAll();
            LogUtils.e(ex.toString());
            Toast.makeText(MeetRecordingActivity.this,"未评价获取数据失败",Toast.LENGTH_LONG).show();
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    };


    /**
     * 已评价列表回调
     */
    private Callback.CommonCallback<String> loadMoreCallback1 = new Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            try{
                JsonObject returnData = new JsonParser().parse(result).getAsJsonObject();
                String returnStr = Base64.getFromBase64(returnData.get("data").getAsString());
                LogUtils.e(returnStr);
                List<Response_meetRecord_item> listData = mGson.fromJson(returnStr,new TypeToken<ArrayList<Response_meetRecord_item>>() {}.getType());
                if(_refreshLayout1.isLoading()){
                    //结束下拉加载弹窗
                    _refreshLayout1.finishLoadmore();
                    mrAdapter1.addListData(listData);
                }else{
                    mrAdapter1.setListData(listData);
                }

                if(listData == null || listData.size() == 0){
                    Toast.makeText(MeetRecordingActivity.this,"已评价没有更多数据了",Toast.LENGTH_LONG).show();
                    return;
                }
                //下次加载页码应+1
                loadPage1++;
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            //结束下拉加载弹窗
            _refreshLayout1.finishLoadmore();
            mrAdapter1.clearAll();
            LogUtils.e(ex.toString());
            Toast.makeText(MeetRecordingActivity.this,"已评价获取数据失败",Toast.LENGTH_LONG).show();
        }
        @Override
        public void onCancelled(CancelledException cex) {
        }
        @Override
        public void onFinished() {
        }
    };



    /**
     * 上拉加载更多
     * @param refreshlayout
     */
    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        if(mFlag == 0){
            Request_getFamilyPhoneList fp = new Request_getFamilyPhoneList
                    (mSelectQueryTime,report_dept_id,report_dept_name,loadPage0,mFlag);
            getMeetRecordListData(fp , loadMoreCallback0);
        }else if(mFlag == 1){
            Request_getFamilyPhoneList fp = new Request_getFamilyPhoneList
                    (mSelectQueryTime,report_dept_id,report_dept_name,loadPage1,mFlag);
            getMeetRecordListData(fp , loadMoreCallback1);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
